package com.yao.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yao.domain.User;
import com.yao.domain.UserExample;
import com.yao.exception.BusinessException;
import com.yao.exception.BusinessExceptionCode;
import com.yao.mapper.UserMapper;
import com.yao.req.UserLoginReq;
import com.yao.req.UserQueryReq;
import com.yao.req.UserResetPasswordReq;
import com.yao.req.UserSaveReq;
import com.yao.resp.UserLoginResp;
import com.yao.resp.UserQueryResp;
import com.yao.resp.PageResp;
import com.yao.util.CopyUtil;
import com.yao.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : hzyao
 * @date : 17:39 2021/7/27
 */
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;
    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);


    public PageResp<UserQueryResp> list(UserQueryReq Req){
        PageHelper.startPage(Req.getPage(),Req.getSize());
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();

        if (!ObjectUtils.isEmpty(Req.getLoginName())){
            criteria.andLoginNameLike("%"+Req.getLoginName()+"%");
        }

        List<User> userList = userMapper.selectByExample(userExample);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());
//        List<UserResp> respList=new ArrayList<>();
//        for (User user : userList) {
//
//            UserResp userResp = CopyUtil.copy(user, UserResp.class);
//            respList.add(userResp);
//        }
        List<UserQueryResp> list = CopyUtil.copyList(userList, UserQueryResp.class);
        PageResp<UserQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     *
     * 新增
     *
     */
    public void save(UserSaveReq req) {
        User user = CopyUtil.copy(req, User.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            User userDB = selectByLoginName(req.getLoginName());
            if (ObjectUtils.isEmpty(userDB)) {
                // 新增
                user.setId(snowFlake.nextId());
                userMapper.insert(user);
            } else {
                // 用户名已存在
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        } else {
            // 更新
            user.setLoginName(null);
            user.setPassword(null);
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    public User selectByLoginName(String LoginName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andLoginNameEqualTo(LoginName);
        List<User> userList = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        } else {
            return userList.get(0);
        }
    }
    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    public void resetPassword(UserResetPasswordReq req) {
        User user = CopyUtil.copy(req,User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 登录
     * @param req
     */
    public UserLoginResp login(UserLoginReq req) {
        User userDB = selectByLoginName(req.getLoginName());
        /* 登录的时候应该给前端返回模糊的错误信息，防止黑客尝试破解，在后端打印详细的日志，用以自己调试 */
        if (ObjectUtils.isEmpty(userDB)) {
            // 用户名不存在
            LOG.info("用户名不存在，{}", req.getLoginName());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }
        if (userDB.getPassword().equals(req.getPassword())) {
            // 登录成功
            UserLoginResp userLoginResp = CopyUtil.copy(userDB, UserLoginResp.class);
            return userLoginResp;
        } else {
            // 密码不对
            LOG.info("密码不对，输入密码：{}，数据库密码：{}", req.getPassword(), userDB.getPassword());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }
    }
}